//
//  ZXOAuthController.m
//  ZXOCWeiBo
//
//  Created by mac on 15/12/3.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZXOAuthController.h"
#import "ZXAccount.h"
#import "ZXTabBarController.h"

@interface ZXOAuthController ()<UIWebViewDelegate>

@property(nonatomic,strong)UIWebView* oauthView;

@end

@implementation ZXOAuthController

- (void)viewDidLoad {
    [super viewDidLoad];
    [SVProgressHUD showWithStatus:@"正在拼命加载" maskType:SVProgressHUDMaskTypeGradient];
    
    //创建一个webVIew
    UIWebView * oauthView = [[UIWebView alloc]initWithFrame:self.view.bounds];
    self.oauthView = oauthView;
    oauthView.delegate = self;
    //加载授权界面
  
    //添加左边的按钮
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"填充" style:UIBarButtonItemStylePlain target:self action:@selector(autoFill)];
    
    NSString * oauthURL = [NSString stringWithFormat: @"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",kclient_id,kredirect_uri];
    
    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:oauthURL]];
    //加载数据
    [oauthView loadRequest:request];
    [self.view addSubview:oauthView];

}

//填充
-(void)autoFill
{

    //创建js代码
    NSString * js = @"document.getElementById('userId').value='403579453@qq.com'; document.getElementById('passwd').value='aini01212'";
    [self.oauthView stringByEvaluatingJavaScriptFromString:js];
}


-(void)accessTokenWithCode:(NSString *)code
{
    NSString * accessTokenURL = @"https://api.weibo.com/oauth2/access_token";
    
    //创建网络请求
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
#warning AFN默认数据返回的处理方式是JSON
//    [AFHTTPResponseSerializer serializer]：设置返回的数据处理方式是二进制
//    [AFJSONResponseSerializer serializer]：设置返回的数据处理方式是JSON 默认
    
    //但是服务器返回的诗歌plain格式的所有我们要转化成二进制然后面在转成字符串
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"client_id"] = kclient_id;
    params[@"client_secret"] = kclient_secret;
    params[@"grant_type"] = kgrant_type;
    params[@"code"] = code;
    params[@"redirect_uri"] = kredirect_uri;
    
    [manager POST:accessTokenURL parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
    //授权成功
//        NSString * respStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
#warning 使用第三方框架直接将二进制转化为模型
  ZXAccount * account =  [ZXAccount objectWithJSONData:responseObject];
        
        if (account.access_token)
        {
//            吧数据保存在沙盒中
            [account saveAccountToSanBox];
            //进入主界面
            ZXTabBarController * tabbarController = [[ZXTabBarController alloc]init];
            [UIApplication sharedApplication].keyWindow.rootViewController = tabbarController;
            ZXLog(@"授权成功");
        }
        
//        NSLog(@"----%@",account);
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        ZXLog(@"%@",error);
    }];
    
    
}

#define mark web的代理方法
/**
 *  询问你链接是否能加载
 */
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    ZXLog(@"%@",request.URL);
    
    if ([request.URL.absoluteString hasPrefix:kredirect_uri])
    {
        NSString * code = [request.URL.query componentsSeparatedByString:@"="][1];
        ZXLog(@"授权成功%@",code);
        //授权成功后，获取accessToken
        [self accessTokenWithCode:code];
        //让返回页面不在UIWeiView上显示
        return NO;
    }
    
    return YES;
}

/**
 *  加载完某个连接的时候调用这个方法
 */
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    //关闭提示
    [SVProgressHUD dismiss];
}


@end
